package com.kaoshi.management.controller;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kaoshi.common.config.Result;
import com.kaoshi.management.pojo.XtSystemNotice;
import com.kaoshi.management.service.XtSystemNoticeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author author
 * @since 2024-10-30
 */
@RestController
@CrossOrigin
@RequestMapping("/notice")
public class XtSystemNoticeController {

    @Autowired
    private XtSystemNoticeService xtSystemNoticeService;

    @PostMapping("/ee/{current}/{pageSize}")
    public Result findAll(@PathVariable Integer current,
                          @PathVariable Integer pageSize,
                          @RequestBody XtSystemNotice xtSystemNotice){
        Page<XtSystemNotice> page =xtSystemNoticeService.findAll(current,pageSize,xtSystemNotice);
        return Result.ok(page);
    }

    @PostMapping("/change")
    public Result change(@RequestBody XtSystemNotice xtSystemNotice) {
        if (xtSystemNotice.getId() == null) {
            xtSystemNotice.setPublisher("李明明");
            xtSystemNotice.setStatus(0);
            xtSystemNoticeService.save(xtSystemNotice);
            return Result.ok("添加成功");
        }else {
            xtSystemNoticeService.updateById(xtSystemNotice);
            return Result.ok("修改成功");
        }
    }

    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id) {
        xtSystemNoticeService.removeById(id);
        return Result.ok("删除成功");
    }

    //导出
    @RequestMapping("/exportExcel")
    public void exportExcel(HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("系统公告", "UTF-8").replaceAll("/+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        //2.查询要导出的数据
        List<XtSystemNotice> studentList= xtSystemNoticeService.list();

        //3.使用EasyExcel完成导出
        EasyExcel.write(response.getOutputStream())
                .head(XtSystemNotice.class)
                .excelType(ExcelTypeEnum.XLSX)
                .sheet("系统公告")
                .doWrite(studentList);

    }



}
